package com.aspyn.threadtest;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

public class ThreadTestActivity extends Activity {
    /** Called when the activity is first created. */
	ProgressBar bar;
	
	boolean barGoing = true;
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (barGoing)
				bar.incrementProgressBy(5);
		}
	};
	boolean isRunning = false;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        bar = (ProgressBar)findViewById(R.id.progBar);
        
        Button btnStart = (Button)findViewById(R.id.btnStart);
        btnStart.setText("Start");
        btnStart.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				barGoing = true;
			}
        	
        });
        
        Button btnStop = (Button)findViewById(R.id.btnStop);
        btnStop.setText("Stop");
        btnStop.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				barGoing = false;
			}
        	
        });
    }
    public void onStart() {
    	super.onStart();
    	bar.setProgress(0);
    	Thread back = new Thread(new Runnable() {
    		public void run() {
    			try {
    				for (int i = 0; i<20 && isRunning; i++) {
    					Thread.sleep(1000);//
    					handler.sendMessage(handler.obtainMessage());
    					if (!barGoing) {
    						i--;
    					}
    				}
    			}
    			catch (Throwable t){ 				
    			}
    		}
    	});//
    	isRunning = true;
    	back.start();
    }
    public void onStop() {
    	super.onStop();
    	isRunning = false;
    	Toast.makeText(this, "Bar filled", 1).show();//Called when program is exited, activity ends
    };
}